package nl.sportan.samenloop.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import nl.sportan.samenloop.R;
import nl.sportan.samenloop.model.Message;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class RssAdapter extends BaseAdapter {

	private static int MINUTE = 60000;
	private static int HOUR = 3600000;
	private static int DAY = 24 * HOUR;
	private static SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");

	List<Message> messages = new ArrayList<Message>();
	Context context;

	public RssAdapter(Context context, List<Message> messages) {
		this.context = context;
		if (messages != null) {
			this.messages = messages;
		}
	}

	public int getCount() {
		return messages.size();
	}

	public Object getItem(int position) {
		return messages.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	private String getPoster(String title) {
		int i = title.indexOf(':');
		if (i != -1 && i < title.length()) {
			String poster = title.substring(0, i);
			return poster;
		}
		
		return "";
	}

	private String stripPoster(String title) {
		int i = title.indexOf(':');
		if (i > 0) {
			String result = title.substring(i + 2);
			return result;
		}
		return title;
	}

	private String convertDate(Date d) {
		long now = new Date().getTime();
		long then = d.getTime();

		if (now - then > DAY) {
			return format.format(d);
		}

		if (now - then > HOUR) {
			long diff = (now / HOUR) - (then / HOUR);
			return diff + " uur";
		}

		if (now - then > MINUTE) {
			long diff = (now / MINUTE) - (then / MINUTE);
			return diff + " min";
		}

		long diff = (now - then);
		return diff + " s";

	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Message m = messages.get(position);

		LinearLayout twitterLayout;

		twitterLayout = (LinearLayout) LayoutInflater.from(context).inflate(
				R.layout.twitter_short, parent, false);

		TextView tv = (TextView) twitterLayout.findViewById(R.id.message);
		TextView poster = (TextView) twitterLayout.findViewById(R.id.poster);
		TextView dateView = (TextView) twitterLayout.findViewById(R.id.date);

		tv.setText(stripPoster(m.getTitle()));
		poster.setText(getPoster(m.getTitle()));
		dateView.setText(convertDate(m.getDate()));

		return twitterLayout;
	}
}
